package com.etoak.filter;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.enums.ResultEnum;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.jwt.JwtUtil;
import com.etoak.common.properties.ImageProperties;
import com.etoak.config.WhiteProperties;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteProperties whiteProperties;

    @Autowired
    private ImageProperties imageProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().value();
        if (whiteProperties.getList().contains(uri) || uri.startsWith(imageProperties.getPrefix())) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token)) {
            //返回
            return noAuth(exchange, ResultEnum.TOKEN_NOT_FOUND_ERROR);
        }
        try {
            JwtUtil.parse(token);
        }catch (ExpiredJwtException e){
            return noAuth(exchange, ResultEnum.TOKEN_TIMEOUT_ERROR);
        }catch (Exception e){
            return noAuth(exchange, ResultEnum.TOKEN_ERROR);
        }


        return chain.filter(exchange);
    }

    private Mono<Void> noAuth(ServerWebExchange exchange, ResultEnum resultEnum) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders()
                .set(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        ResultVO<Object> resultVO = ResultVO.failed(resultEnum);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(resultVO).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
